package com.atguigu.gulimall.auth.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.util.HttpUtils;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.atguigu.common.vo.MemberRespVo;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    public String getId(String accessToken) throws Exception {

        String host = "https://gitee.com";
        String path = "/api/v5/user";
//      String accessToken = "f62dbc1a23e74031097ee4e5352c9f71";
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token",accessToken);

        HttpResponse response = HttpUtils.doGet(host, path, "get", new HashMap<>(), map);

        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSON.parseObject(json);
        String id = jsonObject.getString("id");

//            String json = EntityUtils.toString(response.getEntity());
//            JSONObject jsonObject = JSON.parseObject(json);
//            String name = jsonObject.getString("name");

        return id;
    }

    //登陆成功回调到这，返回一个code，传进去
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {

        //code码前端已经获取到了
        //1,根据code换取access——token

        String host = "https://gitee.com";
        String path = "/oauth/token";
        String method = "POST";
        String clientId = "f28d6080ed5ae533653b32bf41ec8b02b85211f41602c0c527fb9bebde70e277";
        String clientSecret = "7895e6ab8f4d8c3b10fe912ec257ed982cb8b6d2c9bd13543c3512c6d304f109";
        String grant_type = "authorization_code";
        String redirect_uri = "http://auth.gulimall.com/oauth2.0/gitee/success";

        Map<String, String> headers = new HashMap<String, String>();

        Map<String, String> querys = new HashMap<String, String>();

        Map<String, String> bodys = new HashMap<String, String>();

        bodys.put("code",code);
        bodys.put("client_id",clientId);
        bodys.put("client_secret",clientSecret);
        bodys.put("grant_type",grant_type);
        bodys.put("redirect_uri",redirect_uri);

        /**
         * 重要提示如下:
         * HttpUtils请从
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
         * 下载
         *
         * 相应的依赖请参照
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
         */
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

        System.out.println(response.toString());

        if(response.getStatusLine().getStatusCode()==200){
            //获取到了access_token


            String json = EntityUtils.toString(response.getEntity());  //将拿到数据转为json
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            String id = getId(socialUser.getAccess_token());
            socialUser.setId(id);

            System.out.println(socialUser);

            //开始调用member微服务
            //知道当前是哪个社交用户
            R r = memberFeignService.oauthLogin(socialUser);

            if(r.getCode()==0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                System.out.println(data);
                System.out.println("登陆信息"+data.toString());
                //成功就去首页
                System.out.println("ok");
                //登陆的时候将session加入共享领域，data是社交用户的信息
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            }else{

                //失败去登陆页面
                return "redirect:http://auth.gulimall.com/login.html";
            }

            //1）如果是第一进站，自动注册进来，
            // 为当前社交用户生成一个会员信息账号，
            // 以后这个社交账号就对应这个会员

        }else{
            return "redirect:http://gulimall.com/login.html";
        }
        //获取response的body
        //System.out.println(EntityUtils.toString(response.getEntity()));

        //登陆成功跳转回首页
    }
}
